const $ = require('selenium-query');
const { findIndex, propEq, filter, head, pipe } = require('ramda');
const mapSeries = require('async/mapSeries');
const eachSeries = require('async/eachSeries');
const { until } = require('selenium-webdriver');

const _checkPanel = $browser => () => $browser.find('.panel-heading').attr('role')
    .then((role) => {
        if (!role) {
            return _checkPanel($browser)();
        }
        return role;
    });

let prevLectureId;

const _getVideoUrl = $browser => ($item, cb) => {
    let lectureIndex;
    let lectureTitle;
    const tmpObj = {};
    // const $item = $(item);
    // console.log($item);

    const mainLogic = () => $item.find('.lecture__item__link').click()
        .then(() => $item.find('.fx .mr5').eq(1).text())
        .then(idx => (lectureIndex = idx.trim()))
        .then(() => $item.find('.lecture__item__link__name').text())
        .then((title) => {
            lectureTitle = title;
            console.log('lectureTitle => %s', title);
            return Object.assign(tmpObj, {
                title: `${lectureIndex} ${title}`,
            });
        })
        .then(() => {
            const videoPlayer = $browser.find('react-video-player');

            return videoPlayer.attr('lecture-id')
                .then((lectureId) => {
                    console.log('WATCH THIS ::: lectureId => ', lectureId);
                    if (!lectureId) {
                        return $browser.find('.lecture-view--e-book').attr('ng-class')
                            .then((ebookClass) => {
                                if (!ebookClass) {
                                    return _getVideoUrl($browser)($item);
                                }
                                console.log('>>>>>>>> ebook');
                                return $browser.find('.fullscreen .mb30 .btn-default')
                                    .attr('href')
                                    .then(href => ({
                                        label: 'ebook',
                                        src: href,
                                    }));
                            });
                    }

                    if (lectureTitle.indexOf('Quiz') !== -1) {
                        return {
                            label: 'quiz',
                            src: '',
                        };
                    }
                    console.log('BEFORE');
                    console.log('prevLectureId ', prevLectureId);
                    console.log('lectureId ', lectureId);

                    if (prevLectureId === lectureId) {
                        console.log('!!!!!!!!!!!!!!!! ASSET NOT CHANGED !!!!!!!!!!!!!!!!!!');
                        return _getVideoUrl($browser)($item);
                    }

                    prevLectureId = lectureId;
                    console.log('AFTER');
                    console.log('prevLectureId ', prevLectureId);
                    console.log('lectureId ', lectureId);
                    console.log('>>>>>>>> video');
                    return videoPlayer.attr('videojs-setup-data')
                        .then((videoData) => {
                            const highQualityVideo = (item) => {
                                if (findIndex(propEq('label', '1080'))(item) === -1) {
                                    return item.label === '720';
                                }
                                return item.label === '1080';
                            };

                            const targetVideo = pipe(filter(highQualityVideo), head);

                            return targetVideo(JSON.parse(videoData).sources);
                        });
                });
        })
        .then((res) => {
            console.log(JSON.stringify(res, null, 4));
            if (res.label === 'ebook') {
                // return Object.assign(tmpObj, {
                //     ebookURL: res.src,
                // });

                cb(null, Object.assign(tmpObj, {
                    ebookURL: res.src,
                }));
            }

            if (res.label === 'quiz') {
                // return Object.assign(tmpObj, {
                //     quizURL: res.src,
                // });
                cb(null, Object.assign(tmpObj, {
                    quizURL: res.src,
                }));
            }

            // return Object.assign(tmpObj, {
            //     contentURL: res.src,
            // });

            cb(null, Object.assign(tmpObj, {
                contentURL: res.src,
            }));
        });

    setTimeout(() => {
        mainLogic();
    }, 3000);
};

const getLectureInfo = browser => (courseInfo) => {
    courseInfo.forEach((course, index) => {
        if (index !== 0) {
            return;
        }
        browser.get(course.link);

        const $browser = $(browser);
        const checkPanel = _checkPanel($browser);
        const getVideoUrl = _getVideoUrl($browser);
        const lectureList = [];

        checkPanel()
            .then(() => $browser.find('.lecture__item').toArray())
            .then((lectureArr) => {
                console.log('lectureArr is Array? =>', Array.isArray(lectureArr));
                console.log(lectureArr.length);

                lectureArr.forEach((item) => {
                    lectureList.push($(item));
                });

                mapSeries(lectureList, getVideoUrl, (err, res) => {
                    if (err) {
                        console.log(err);
                    }
                    console.log(res);
                });
            });
            // .then(res => console.log('lecture info arr is: \n', res));
    });
};

module.exports = getLectureInfo;
